/**
* @CopyRight tstudy.com.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.group;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.BaseOnScrollListener;
import com.tstudy.laoshibang.base.BaseOnScrollListener.FirstPositionCallBack;
import com.tstudy.laoshibang.base.BaseOnScrollListener.LoadMoreCallBack;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.CONSTANT.LoadType;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.custom.RoundImageView;
import com.tstudy.laoshibang.event.ChangeGroupEvent;
import com.tstudy.laoshibang.group.GroupAdapter.AdapterCallBack;
import com.tstudy.laoshibang.manager.GroupManager;
import com.tstudy.laoshibang.mode.TGroup;
import com.tstudy.laoshibang.mode.request.Conds;
import com.tstudy.laoshibang.mode.response.GroupListResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
@SuppressLint("InflateParams")
@EFragment(R.layout.my_group)
public class MyGroupFragment extends BaseFragment{
	final static String TAG = "my_group";
	public MyGroupFragment() {
		super();
	}
	
	@ViewById(R.id.my_group_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.my_group_progress)
	RelativeLayout mProgressLayout;
	
	@ViewById(R.id.my_group_list)
	PullToRefreshListView mPullToRefreshListView;
	
	@ViewById(R.id.my_group_title)
	TextView mTitleTxt;
	@ViewById(R.id.my_group_empty_layout)
	RelativeLayout mEmptyLayout;

	BaseOnScrollListener mBaseOnScrollListener;
	LoadType mLoadType;
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	GroupAdapter mMyGroupAdapter;
	int mCurrentPosition = 0;
	List<TGroup> mMyGroups = new ArrayList<TGroup>();

	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,MyGroupFragment_.class.getName(),args);
		((BaseActivity)BaseApplication.mCurrentActivity).add(containerViewId,fragment,TAG);	
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		EventBus.getDefault().register(this);
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			mMyGroupAdapter = new GroupAdapter(false);
			mPullToRefreshListView.setAdapter(mMyGroupAdapter);
			mMyGroupAdapter.setAdatperCallBack(new AdapterCallBack() {
				@Override
				public void onViewClick(String groupId, int position) {
					GroupProfileFragment.add(mFragmentId, groupId);
				}
				@Override
				public void onAddClick(TGroup group, int position) {
					GroupProfileFragment.add(mFragmentId, group.groupId);
				}
				@Override
				public void onEnterClick(TGroup group, int position) {
					group.isSelect = 1;
					BaseApplication.mCurrentGroup = group;
					EventBus.getDefault().post(new ChangeGroupEvent());
					GroupManager.getInstance().clear(TGroup.class);
					GroupManager.instance.insert(group);
					backAction(mFragmentId);
					
				}
			});
			mLoadType = LoadType.load_first;
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
					getMyGroupList();
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
			mBaseOnScrollListener = new BaseOnScrollListener(new LoadMoreCallBack() {
				@Override
				public void loadMore() {
					mPullToRefreshListView.startLoadMore();
					mLoadType = LoadType.load_more;
					getMyGroupList();
				}
			});
			mBaseOnScrollListener.setFirstPositionCallBack(new FirstPositionCallBack() {
				@Override
				public void firstPosition(int firstPosition) {
					mCurrentPosition = firstPosition;
				}
			});
			mPullToRefreshListView.setOnScrollListener(mBaseOnScrollListener);
			mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				@Override
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					mLoadType = LoadType.load_refresh;
					getMyGroupList();
				}
			});
		}
	}
	
	@Click({R.id.my_group_back,R.id.my_group_all_icon})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.my_group_back:
			backAction(mFragmentId);
			break;
		case R.id.my_group_all_icon:
			GroupRecommendFragment.add(mFragmentId);
			break;
		default:
			break;
		}
	}
	
	RelativeLayout mHeaderLayout;
	RoundImageView mAvatar;
	ImageView mTheme;
	TextView mName;
	
	private void getMyGroupList(){
		if (mIsLoading) {
			return ;
		}
		if (mLoadType == LoadType.load_more) {
			start += pageSize;
//			limit += pageSize;
		}else{
			start = 0;
			limit = pageSize;
		}
		mIsLoading = true;
		BaseListJsonHandler<GroupListResponse> response = new BaseListJsonHandler<GroupListResponse>() {
			public void onStart() {
				if (mLoadType == LoadType.load_first) {
					showProgressBar(mProgressLayout);
				}
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, GroupListResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mLoadType == LoadType.load_more) {
						if (mMyGroups.size() == response.getData().getCount()) {
							mBaseOnScrollListener.mIsEnd = true;
						}
					}else{
						mMyGroups.clear();
					}
					if (response.getData() != null) {
						List<TGroup> list = response.getData().getList();
						if (list != null) {
							mMyGroups.addAll(list);
						}
						if (mMyGroups.size() > 0) {
							mEmptyLayout.setVisibility(View.GONE);
						}else{
							mEmptyLayout.setVisibility(View.VISIBLE);
						}
						mMyGroupAdapter.setData(mMyGroups);
					}
				}else{
					BaseApplication.showToast(response.getErrMsg());
					
				}
				afterLoading();
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					GroupListResponse errorResponse) {
				afterLoading();
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected GroupListResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,GroupListResponse.class);
			}
		};
		List<Conds> conds = new ArrayList<Conds>();
		HttpManager.getInstance().getJoinList(BaseApplication.mUserNo, start, limit, null, conds, response);
	}
	
	public void onEventMainThread(Object object) {//申请成功后更新列表
		mLoadType = LoadType.load_first;
	}

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
		if(mLoadType == LoadType.load_more){
			if (mBaseOnScrollListener.mIsEnd) {
				mPullToRefreshListView.endLoadMore(BaseApplication.getResString(R.string.group_no_more_data));
			}else{
				mPullToRefreshListView.stopLoadMore();
			}
		}
		if(mPullToRefreshListView != null){
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					if(mPullToRefreshListView != null){
						mPullToRefreshListView.onRefreshComplete();
						LogUtil.d("--onRefreshComplete afterloading");
					}
				}
			}, 1000);
		}
	}
	@Override
	public void clear() {
	}
	
	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
